import sys
import psycopg2.pool,requests,logging,os
from db import *
from functools import *




def initLog():
    BASE_DIR=os.path.dirname(__file__)
    logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(module)s.%(funcName)s.%(lineno)d %(levelname)-8s %(message)s',filename=BASE_DIR+'/log/'+dtLabelStr(is_split=1)+'.log',filemode='w+')
    console=logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter=logging.Formatter('%(asctime)s - %(module)s.%(funcName)s.%(lineno)d %(levelname)-8s %(message)s')
    console.setFormatter(formatter)
    getLogger('').addHandler(console)



def now():
    return datetime.datetime.now()

def dtLabelStr(is_split=0):
    r=str(datetime.datetime.now())[:-7].replace(' ','').replace(':','').replace('-','')
    if is_split==1:r=r[:8]+'-'+r[8:]
    return r

def dtStr():
    return str(datetime.datetime.now())[:-7]


def deleteRepeat(l):
    for x in l:
        while l.count(x)>1: del l[l.index(x)]




def logExcept():
    type,value,tb=sys.exc_info()
    tb_format=traceback.format_exception(type,value,tb)
    getLogger('').exception(tb_format)
    return tb_format


def db_deco(p=None):
    def decoFunction(f):
        @wraps(f)
        def wrapFunction(*args,**kwargs):
            with DBConnection(p.getconn()) as con:
                cur=con.cursor()
                kwargs={'con':con,'cur':cur}
                return f(*args,**kwargs)
        return wrapFunction
    return decoFunction


def sqlStr(s):
    if s==None: return 'null'
    if type(s)==str:return "'"+s+"'"
    if type(s)==list or type(s)==tuple:
        r=str(tuple(s))
        if r[-2:]==',)':r=r[:-2]+r[-1]
        return r



    else:return str(s)


def d2j(d,i=0):return json.dumps(d,ensure_ascii=0,indent=i)



